package com.tiny.controller;

import java.util.Date;

import org.apache.shiro.authz.annotation.RequiresAuthentication;

import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.tiny.model.User;
import com.tiny.model.UserRole;

public class UserController extends Controller {

	public void index() {
		render("/frame/user.html");
	}
	
	public void query(){
		StringBuilder sql = new StringBuilder(" from user where 1=1 ");

		if (StrKit.notBlank(this.getPara("username"))) {
			sql.append(String.format(" and username like '%s%%' ",
					this.getPara("username")));
		}

		if (StrKit.notBlank(this.getPara("sort"))) {
			sql.append(String.format("%s %s %s", "order by",this.getPara("sort"),this.getPara("order")));
		}
		else{
			sql.append(" order by id desc ");
		}
		
		Page<User> page = User.dao.paginate(this.getParaToInt("page"), this.getParaToInt("rows"),"select * ", sql.toString());
		
		renderJson(page.getList());
	}
	
	public void add(){
		User user = getModel(User.class);
		
		user.set("username", this.getPara("username"));
		user.set("create_time", new Date());
		user.set("password", "1");
		user.set("id", 0);

		user.save();
		
		setAttr("errorMsg", false);
		renderJson();
	}
	
	public void edit(){
		User user = getModel(User.class);
		
		user.set("username", this.getPara("username"));
		user.set("id", this.getPara("id"));
		user.update();
		setAttr("errorMsg", false);
		renderJson();
	}
	
	public void remove(){
		setAttr("success", User.dao.deleteById(this.getPara("id")));
		renderJson();
	}
	
	public void getRoles(){
		renderJson(Db.find(" select role_id as id from UserRole where user_id=? ",this.getPara("id")));
	}
	
	public void manageRole(){
		Db.update(" delete from UserRole where user_id=? ",this.getPara("id"));
		Integer[] pids=this.getParaValuesToInt("role_id");
		for(Integer id:pids){
			UserRole ur=new UserRole();
			ur.set("user_id", this.getPara("id"));
			ur.set("role_id", id);
			setAttr("success", ur.save());
		}
		renderJson();
	}

}